import React, { Component } from 'react';
import { Divider, Row, Col, List, Avatar, Icon, Badge, Card, Upload, Button, message, Modal, Table, Progress, Affix, Menu, Select, Collapse } from 'antd';
import PropTypes from 'prop-types';
import { API_DOMAIN, QINIU_DOMAIN } from '../../../utils/constants';
import './Home.scss';
import { execFile } from 'child_process';
import API from '../../../api/files/index';
import TokenAPI from '../../../api/auth/index';
import * as qiniu from 'qiniu-js';
import pdfAPI from '../../../api/pdf/index'
import QueueAnim from 'rc-queue-anim';
import Dashboard from '../../containers/dashboard/main/main'
// import ProjectData from '../../containers/Project/data/main'
// import WrappedFileManage from '../../containers/Project/list/ProjectList'
import MainManage from '../../containers/Project/manage/MainManage'
const accessToken = window.localStorage.getItem('accessToken');
const refreshToken = window.localStorage.getItem('refreshToken');
const classNames = require('classnames');
const Dragger = Upload.Dragger;
const props = {
  name: 'excelFile',
  multiple: true,
  templateId: "5ab342a3418287ad3b9038fe",
  action: `${API_DOMAIN}/legal/document/batchAdd.htm`,
  headers: {
    'Access-Token': accessToken,
    'Refresh-Token': refreshToken,
  },
  data: {
    templateId: "5ab342a3418287ad3b9038fe"
  },

  onChange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} 文件上传成功.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};
const data = [
  {
    name: 'vivi',
    title: '关于磐晟会议室项目立项',
    time: '2018-9-11 20:05'
  },
  {
    name: 'vivi',
    title: '回复：文件材料运输问题',
    time: '2018-9-11 20:05'
  },
  {
    name: 'vivi',
    title: '人事招聘事宜',
    time: '2018-9-11 20:05'
  },

];

function GetGreetings() {  
  var now = new Date();  
  var times = now.getHours();  
  var whe=parseInt(times);  
  if(times>=4 && times<7){return "早上好，早起的鸟儿有虫吃！"}  
  if(times>=7 && times<9){return "早上好，愿您微笑每一天！"}  
  if(times>=9 && times<11){return "上午好，一帆风顺！"}  
  if(times>=11 && times<13){return "中午好，别忘记吃饭哟！"}  
  if(times>=13 && times<17){return "下午好，工作加油，精神抖擞！"}  
  if(times>=17 && times<19){return "傍晚好，再接再励！"}  
  if(times>=19 && times<22){return "晚上好，保持精力，继续战斗！"}
  if(times>=22 && times<24){return "夜深了，感谢您辛勤的工作！"} 
} 


const noticeData = [{
  message: '磐晟云平台正式版已经上线！感谢大家一直以来的支持，请大家在各大应用平台搜索“磐晟云”下载应用。',
  time: '2018-04-23 09:00'
},
{
  message: ' 集团将于4月25日在上海举行盛大招募会，请相关部门做好协调工作',
  time: '2018-04-23 09:00'
}
]

const EditableCell = ({ editable, value, onChange }) => (
  <div>
    <img src="/images/icon_excel.png" style={{ width: 30, height: 30 }} /> {editable ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} /> : value}
  </div>
);
class Notice extends Comment {
  constructor(props) {
    super(props);
  }
  render() {
  }
}

class Email extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <Row style={{ padding: 15 }}>
          <Badge count={5}><span style={{ fontSize: 20 }}>未读邮件</span></Badge>
          <h3 style={{ float: "right" }}>查看更多</h3>
        </Row>
        {
          this.props.data.map((item, idx) => (
            <Row key={idx} style={{ marginTop: 5, marginLeft: 15, marginRight: 15 }}>
              <Col span={3}><Icon type="mail" /></Col>
              <Col span={4}>{item.name}</Col>
              <Col span={9}>{item.title}</Col>
              <Col span={8}>{item.time}</Col>
            </Row>
          ))
        }
      </div>
    )

  }
}

class Note extends Component {

  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3 style={{ marginLeft: 15, marginBottom: 10 }}>公告</h3>
        {this.props.data.map((item, idx) => (
          <Row style={{ marginTop: 10 }} key={idx}>
            <Col span={1} push={1}><Icon type="notification" style={{ color: "red" }} /></Col>
            <Col span={14} push={1}>{item.message}</Col>
            <Col span={7} push={2}>{item.time}</Col>
          </Row>
        ))
        }
      </div>
    )
  }
}


const Panel = Collapse.Panel;

class PdfTemplate extends Component {
  state = {
    dirCount: 0,
    fileCount: 0,
    dataSource: [],
    visibleOfDir: false,
    visibleOfFile: false,
    dirName: '',
    uploadedFiles: [],
    name: "",
    nameList: [],
    templateData: [],
    currentTemplate: {},
    selectTemplateId: null,
    currentExcelUrl: "",
    batchData: null,
    taskList: [],
    visibleTask: false,
  }
  constructor(props) {
    super(props)
    this.loadTemplateList();
    // setInterval(()=>{
    //   if(this.state.batchData!=null){
    //     this.getBatchList()
    //   }

    // },5000)
  }

  getBatchList = async () => {
    const res = await pdfAPI.getBatchList(this.state.id, this.state.batchData.id);
    const { code, data } = res;
    if (code == 1) {
      this.setState({ taskList: data, visibleTask: true })
    } else {
      message.error("没有找到当前协议")
    }
  }

  CreateTemplate = async (url, id) => {
    const res = await pdfAPI.createTemplate(url, id);
    const { code, data, msg } = res;
    if (code == 1) {
      this.setState({ batchData: data, visibleOfFile: false })
      message.success("模板协议任务提交成功")
      this.getBatchList();
    } else {
      message.error("文件解析错误")
    }
  }
  handleSelectTemplateId = (key) => {
    console.log(key)
    this.setState({ selectTemplateId: key.id })
  }

  handleTemplateChange = (key) => {
    console.log(key)
    this.setState({ currentTemplate: key, selectTemplateId: key.id })
  }

  remove(index) {
    const uploadedFiles = this.state.uploadedFiles
    uploadedFiles.splice(index, 1)
    this.setState({ uploadedFiles })
  }
  edit(uid) {
    const newData = [...this.state.uploadedFiles];
    const target = newData.filter(item => uid === item.uid)[0];
    if (target) {
      target.editable = true;
      this.setState({ uploadedFiles: newData });
    }
  }
  save(uid) {
    const newData = [...this.state.uploadedFiles];
    const target = newData.filter(item => uid === item.uid)[0];
    if (target) {
      delete target.editable;
      this.setState({ uploadedFiles: newData });
      this.cacheData = newData.map(item => ({ ...item }));      this.cacheData = newData.map(item => ({ ...item }));
    }
  }
  cancel(uid) {
    const newData = [...this.state.uploadedFiles];
    const target = newData.filter(item => uid === item.uid)[0];
    if (target) {
      Object.assign(target, this.cacheData.filter(item => uid === item.uid)[0]);
      delete target.editable;
      this.setState({ uploadedFiles: newData });
    }
  }
  renderColumns(text, record, column) {
    return (
      <EditableCell
        editable={record.editable}
        value={text}
        onChange={value => this.handleChange(value, record.uid, column)}
      />
    );
  }

  loadTemplateList = async () => {
    const res = await pdfAPI.getTemplateList()
    console.log(res)
    const { data } = res
    this.setState({ templateData: data })
  }
  handleHideModal = () => {
    this.setState({
      visibleOfFile: false,
    });
  }

  handleShowModal = () => {

    this.setState({
      visibleOfFile: true,
      uploadedFiles: []
    })
  }
  finishUpload = ({ file }) => {
    const { status } = file.status;
    if (status === 'done') {
      this.state.uploadedFiles.filter((item, index) => {
        if (item.uid === file.uid) {
          item.percent = 100;
        }
      });
    }
  }
  handleUpload = async ({ file }) => {
    const response = await TokenAPI.getUploadToken();
    const { code, data } = response;
    if (code === 1) {
      const fileName = file.name.substr(0, file.name.lastIndexOf('.'));
      const ext = file.name.substr(file.name.lastIndexOf('.') + 1);
      const fileObj = {
        uid: file.uid,
        size: file.size,
        nickname: fileName,
        fullname: file.name,
        url: '',
        parent: this.state.currentId,
        format: ext,
        percent: 0,
        tags: [],
        security: ['agreement'],
      };
      this.setState({
        uploadedFiles: [fileObj],
      });
      const token = data;
      const config = {
        useCdnDomain: true,
      };
      const putExtra = {
        fname: '',
        params: {},
        mimeType: null,
      };
      const next = async ({ total }) => {
        const { percent } = total;
        const { uploadedFiles } = this.state;
        uploadedFiles.filter((item, index) => {
          if (item.uid === file.uid) {
            const tempObj = Object.assign({}, item, { percent: parseInt(percent) });
            uploadedFiles.splice(index, 1, tempObj);
            this.setState({ uploadedFiles });
          }
        });
      };
      const complete = async (res) => {
        const url = `${QINIU_DOMAIN}/${res.key}`;
        const response = await TokenAPI.getDownloadUrl(url);
        const { code, data } = response;
        if (code === 1) {
          let uploadedFiles = this.state.uploadedFiles
          const tempObj = uploadedFiles[uploadedFiles.length - 1]
          tempObj.url = data
          uploadedFiles.splice(uploadedFiles.length - 1, 1, tempObj)
          this.setState({
            uploadedFiles
          })
        }
      };
      const observable = qiniu.upload(file, null, token, putExtra, config);
      observable.subscribe(next, undefined, complete);
    } else {
      message.error('token获取失败');
    }
  }

  handleUploadFile = async () => {
    const uploadedFiles = this.state.uploadedFiles
    if (uploadedFiles.length === 0) {
      message.warn('请先上传文件')
    } else if (uploadedFiles.length === 1) {
      this.CreateTemplate(this.state.uploadedFiles[0].url, this.state.selectTemplateId);

    }

  }

  handleShowTaskModel = async () => {

    // if (this.state.batchData != null) {
    //   this.setState({ visibleTask: true })
    //   this.getBatchList()
    // } else {
    //   message.info("当前没有协议任务")
    // }
    const res = await pdfAPI.getHistoryList()
    const { data, code, msg } = res;
    if (code == 1) {
       this.props.pdfShow(data);
    } else {
      message.error("读取历史任务出错")
    }

  }

  handleDownTemplate = () => {
    // console.log(templateItem)
    // console.log(process) 
    window.open(this.state.currentTemplate.excelUrl)
  }

  handleDownFile = async (key) => {
    const res = await pdfAPI.getDownDocument(key.id);
    const { data, code, msg } = res;
    console.log(data)
    if (code == 1) {
      window.location.href = encodeURI(data + "&attname=" + key.nickname + ".pdf")
    } else {
      message.error(msg);
    }

  }

  render() {
    const uploadedFilesColumns = [{
      title: 'Excel文件名称',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (text, record) => this.renderColumns(text, record, 'nickname'),
    }, {
      title: '传输进度',
      dataIndex: 'percent',
      key: 'percent',
      render: (text, record) => (<Progress percent={record.percent} />),
    }, {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record, index) => {
        const { editable } = record;
        return (
          <div className="editable-row-operations">
            {editable ?
              <a onClick={() => this.save(record.uid)}>保存</a>
              : (
                <span>
                  {/* <a onClick={() => this.edit(record.uid)}>编辑</a>
              <Divider type="vertical" /> */}
                  <a onClick={() => this.remove(index)}>删除</a>
                </span>
              )
            }
          </div>
        );
      },
    }];


    return (
      <Row className="pdfView">
        <Modal
          width={800}
          title="任务"
          visible={this.state.visibleTask}
          // visible={true}
          okText="确定"
          cancelText="取消"
          onOk={() => this.setState({ visibleTask: false })}
          onCancel={() => this.setState({ visibleTask: false })}
        >

          {
            this.state.taskList.map(item => (
              <Row style={{ marginTop: 10 }} key={Math.random()}>
                <Col span={1}><Icon type="file-pdf" style={{ color: "red" }} /> </Col>
                <Col span={21}>{item.nickname}</Col>
                <Col span={2}><a onClick={this.handleDownFile.bind(this, item)}>下载</a></Col>
              </Row>))
          }

        </Modal>



        <Modal
          width={800}
          title={`模板：${this.state.currentTemplate.nickname}`}
          visible={this.state.visibleOfFile}
          okText="立即转换"
          cancelText="取消"
          onOk={this.handleUploadFile}
          onCancel={this.handleHideModal}
        >
          <Row>
            <Col span={6}>
              <Upload
                accept=".xlsx"
                showUploadList={false}
                customRequest={this.handleUpload}
                onChange={this.finishUpload}
              >
                <Button type='primary' icon="upload">上传Execl</Button>
              </Upload>
            </Col>
            <Col span={14} className="downLoadPDF">
              <p style={{ textAlign: "center", fontSize: 12, color: "#B0B0B0", marginTop: 5 }}>必须上传模板格式文件，若没有模板，请先下载</p>
              <Row type="flex" justify="center" style={{ marginTop: 10 }}>

                <span style={{ marginTop: 5 }}>{this.state.currentTemplate.nickname}</span>

                <Button type="primary" style={{ marginLeft: 10 }} onClick={this.handleDownTemplate}>下载</Button>

              </Row>
            </Col>
          </Row>
          <Divider />
          <Table rowKey="uid" dataSource={this.state.uploadedFiles} columns={uploadedFilesColumns} />

        </Modal>
        <p style={{ marginLeft: 20, marginTop: 10, color: "rgba(59,58,66,1)", fontSize: 20 }} type="flex" justify="center" align="top">自动化模版协议</p>
        <Row style={{ fontSize: 14, marginTop: 10, color: "rgba(176,176,176,1)", textAlign: "center" }} type="flex" justify="center">
          <Col span={18}>将数据导入到模板，进行上传，可以转化为不同客户的PDF文件</Col>
        </Row>
        <Row style={{ marginTop: 15 }}>
          <Col span={24}>
            <span>模板：</span>
            <Select  key={Math.random()} style={{ marginLeft: 5, marginTop: 5, width: 220 }} placeholder="请选择协议模板" onChange={this.handleTemplateChange}>
              {
                this.state.templateData.map((item, idx) => (
                  <Option value={item} key={idx}>
                    {item.nickname}
                  </Option>
                ))
              }

            </Select>
          </Col>
        </Row>


        <Row style={{ marginTop: 40 }}>
          <Button onClick={this.handleShowModal} type="primary" disabled={this.state.selectTemplateId == null ? true : false} >上传Execl并转换</Button>
        </Row >
        <Row style={{ marginTop: 20 }}>
          <a onClick={this.handleShowTaskModel} className="aLink"><Icon type="clock-circle-o" style={{ marginRight: 5 }} />转换记录</a>
        </Row>

      </Row>
    )
  }
}

class BatchList extends Component {
  state = {
    list: [],
    id: null,

  };
  constructor(props) {
    super(props)
    this.setState({ id: this.props.id })
  };
  getBatchList = async (batchid) => {
    const res = await pdfAPI.getBatchList(null, batchid);
    const { code, data } = res;
    if (code == 1) {
      this.setState({ list: data })
    } else {
      message.error("没有找到当前协议")
    }
  }
  componentDidMount() {
     this.getBatchList(this.props.id)
  }
  handleDownFile = async (key) => {
    const res = await pdfAPI.getDownDocument(key.id);
    const { data, code, msg } = res;
    console.log(data)
    if (code == 1) {
      window.location.href = encodeURI(data + "&attname=" + key.nickname + ".pdf")
    } else {
      message.error(msg);
    }

  }
  render() {
    return (
      <div>
        {
          this.state.list.map(taskItem => (
            <Row style={{ marginTop: 5 }} key={Math.random()}>
              <Col span={1}><Icon type="file-pdf" style={{ color: "red" }} /> </Col>
              <Col span={21}>{taskItem.nickname}</Col>
              <Col span={2}><a onClick={this.handleDownFile.bind(this, taskItem)}>下载</a></Col>
            </Row>
          ))
        }
      </div>
    )
  }
}

const customPanelStyle = {
  borderRadius: 4,
  border: 0,
  overflow: 'hidden',
  background:'#F7F7F7', 
};

class PdfTaskWindow extends Component {
  state = {
    show: true,
    data: [],
    taskList: {},

  };
  constructor(props) {
    super(props)
    this.setState({ show: this.props.show, data: this.props.data })
  };

  componentWillReceiveProps(nextProps) {
    this.setState({ show: nextProps.show, data: nextProps.data })
   

  }
  componentDidMount() {
    this.setState({ show: this.props.show, data: this.props.data })
  }

  confirm = (e) => {
    e.stopPropagation();
  }
  onchange = (item) => {
    //this.getBatchList(item.id)
  }

  render() {
    return (
      <QueueAnim delay={300} onClick={this.confirm}>
        {this.state.show ? [
          <div className="PdfTaskWindow" key="a">

            {
              this.state.data.map((item, idx) => (
              <Row style={{marginBottom:20}}>
               
                <Collapse bordered={false} key={idx} onChange={this.onchange.bind(this, item)}>
             
                  <Panel onClick={this.test} header={item.template.nickname} style={customPanelStyle}>
             
                      <Row style={{ marginTop: 5}}>
                      <BatchList id={item.id} />
                  </Row>
                  </Panel>
                  <div style={{background:'#F7F7F7',fontSize:14,color:"#B0B0B0"}}>

                  <span style={{marginLeft:15}}>{item.size}个文件</span>
                  <span className="floatRight">{item.createdAt}</span>
                </div>
                </Collapse>
                
                </Row>
              ))
            }
          </div>
        ] : null}

      </QueueAnim>
    );
  }
}

class Home extends Component {
  state = {
    data: null,
    visible: true,
    show: false,
    greetTime:GetGreetings(),
    account: JSON.parse(window.sessionStorage.getItem('account')) || {}
  }
  componentWillReceiveProps(nextProps) {

    this.setState({
      visible: nextProps.visible,
    });
  }
  handlepPdfWindowShow = (data) => {
    this.setState({ show: !this.state.show, data: data })
  }
  handleHideTask=()=>{
  
      if(this.state.show){
        this.setState({show:false})
      }
  }
  componentDidMount(){


  }
  render() {
    const { account } = this.state;
    const className = classNames('home', { hide: !this.state.visible });
    const lengthOfdepartments = account.department.length;
    return (
      <div className={className} onClick={this.handleHideTask}>
      <MainManage />
{/* <ManageDetail id={"5b04de0ffc4635302367c879"} /> */}
{/* <WrappedFileManage /> */}

        {/* <header>
          <div className="ant-breadcrumb">
            {
              account.department.map((item, index) => {
                const classNameOfSpan = classNames({ hide: index === (lengthOfdepartments - 1) });
                return (
                  <span key={Math.random()}>
                    {item.nickname}<span className={classNameOfSpan}> &gt; </span>
                  </span>
                );
              })
            }
            <Divider type="vertical" /> {account.company.title}
          </div>
          <div className="tips">{account.nickname}，{GetGreetings()}</div>
        </header> */}
            

        
      

        {/* {

          <div >
            <Row className="hide">
              <div className="headView">
                <div className="emailView"  >
                  <Email data={data} />
                </div>
                <div className="noticeView" >
                  <Note data={noticeData} />
                </div>
              </div>
            </Row>
            
          
            <Row className="tools">
            <Row className="toolsTitle"><span style={{marginLeft:20}}>小工具</span></Row>
              <PdfTaskWindow show={this.state.show} data={this.state.data} />
              <Col span={7} className="panel" style={{ paddingTop: 10, height: 300 }}>
                <PdfTemplate pdfShow={this.handlepPdfWindowShow} />
              </Col>
              <Col span={6} className="panel hide">
                <Dragger accept=".xlsx" name="excelFile">
                  <p className="ant-upload-drag-icon">
                    <Icon type="inbox" />
                  </p>
                  <p className="ant-upload-text">文件添加水印</p>
                  <Button>
                    <Icon type="upload" />选择文件
                    </Button>
                </Dragger>
              </Col>
              <Col span={6} className="panel" style={{ textAlign: "center", paddingTop: 30 }}>
                <h3>更多小工具</h3>
                <h5>敬请期待</h5>
              </Col>
            </Row>
          </div>

        } */}
      </div>
    );
  }
}

Home.propTypes = {
  visible: PropTypes.bool.isRequired,
};

export default Home;
